<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    .box {
        position: relative;
        width: 400px;
        height: 10px;
        background-color: green;
        margin: 50px auto;
    }

    .box>.bar {
        position: absolute;
        top: -5px;
        width: 10px;
        height: 20px;
        background-color: red;
        cursor: pointer;
    }

    .box>.mask {
        position: absolute;
        top: 0;
        left: 0;
        height: 10px;
        background-color: red;
    }
    p{
        text-align: center;
        color: red;
        font-size: 20px;
    }
</style>

<body>
    <div class="box">
        <div class="bar"></div>
        <div class="mask"></div>
    </div>
    <p></p>
</body>
<script>
    var box = document.querySelector('.box')
    var bar = document.querySelector('.bar')
    var mask = document.querySelector('.mask')
    var p = document.querySelector('p')

    bar.onmousedown = function (event) {
        event = event || window.event //浏览器兼容
        var barLeft = this.offsetLeft  //bar框的最左边为参照
        var initLeft = event.clientX  //浏览器最左边为参照

        //鼠标移动事件
        document.onmousemove = function (event) {
            event = event || window.event //浏览器兼容
            var moveX = event.clientX - initLeft + barLeft
            if (moveX > box.offsetWidth - bar.offsetWidth) {
                moveX = box.offsetWidth - bar.offsetWidth
            } else if (moveX < 0) {
                moveX = 0
            }
            mask.style.width = moveX + 'px'
           
            bar.style.left = moveX + 'px'
            //.toFixed(2) 保留两位小数
            var percent = ((moveX / (box.offsetWidth - bar.offsetWidth))*100).toFixed(2)+'%'
            window.getSelection() ? window.getSelection().removeAllRanges() : document.selection.empty(); 
            p.innerHTML='已经走了'+percent
        }
        document.onmouseup = function(){
            document.onmousemove=""
        }
    }
</script>

</html>